<?php

namespace app\api\controller;

use app\common\model\Advice;
use app\common\model\DriverInfo;
use app\common\model\MoneyLog;
use app\common\model\Notice;
use app\common\model\SubOrder;
use fast\Random;
use think\facade\Validate;
use think\facade\Config;
use fast\Http;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\controller\Api;
use app\common\model\User as UserModel;

/**
 * 会员接口.
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changemobile', 'third','getUnionId','wxlogin','getWxPhone'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心.
     */
    public function index()
    {
        $user=$this->auth->getUserinfo();

        $user_type=request()->param('user_type','user_miniapp');

        $driver_info=DriverInfo::where(['user_id'=>$user['id']])->find()?:[];
        $user['driver_info']=$driver_info;

        /*$user['total_money']=SubOrder::where([['status','in',[6,7]],['driver_id','=',$user['id']]])
            ->sum('driver_money');*/
        $user['total_money']=MoneyLog::where(['user_id'=>$user['id']])
            ->sum('money');

        $today_time=strtotime(date('Y-m-d').' 00:00:00');
        /*$user['today_money']=SubOrder::where([['status','in',[6,7]],['driver_id','=',$user['id']],['finish_time','>',$today_time]])
            ->sum('driver_money');*/
        $user['today_money']=MoneyLog::where([['user_id','=',$user['id']],['createtime','>',$today_time]])
            ->sum('money');

        $user['money_log']=MoneyLog::where(['user_id'=>$user['id']])->order('createtime desc')->limit(0,5)->select()?:[];

        $this->success('成功',$user);
    }

    /**
     * 会员登录.
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (! $account || ! $password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];

            $data['driverinfo']=DriverInfo::where(['user_id'=>$data['userinfo']['id']])
                ->field('name,status')
                ->find()?:null;
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录.
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (! $mobile || ! $captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (! Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (! Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::where('mobile',$mobile)->find();
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员.
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        if (! $username || ! $password) {
            $this->error(__('Invalid parameters'));
        }
        if ($mobile && ! Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        if (empty($mobile)) {
            $mobile = $username;
        }
        $ret = $this->auth->register($username, $password, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录.
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息.
     *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');

        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }

        $user->save();
        $this->success();
    }

    /**
     * 修改手机号.
     *
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (! $mobile || ! $captcha) {
            $this->error(__('请填写正确的手机号码与验证码'));
        }
        if (! Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('请填写正确的手机号码'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('手机号码已被使用'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (! $result) {
            $this->error(__('验证码不正确'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录.
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request('platform');
        $code = $this->request->request('code');
        $config = get_addon_config('third');
        if (! $config || ! isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result,
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $mobile = $this->request->request('mobile');
        $newpassword = $this->request->request('newpassword');
        $captcha = $this->request->request('captcha');
        if (! $newpassword || ! $captcha) {
            $this->error(__('Invalid parameters'));
        }

        if (! Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $user = \app\common\model\User::where('mobile',$mobile)->find();
        if (! $user) {
            $this->error(__('User not found'));
        }
        $ret = Sms::check($mobile, $captcha, 'resetpwd');
        if (! $ret) {
            $this->error(__('Captcha is incorrect'));
        }
        Sms::flush($mobile, 'resetpwd');

        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 授权
     */
    public function getUnionId(){
        $code = $this->request->request('code');
        $type=request()->param('type','user_miniapp');

        if(!$code)
            $this->error('code参数错误');
        if(!in_array($type,['user_miniapp','driver_app']))
            $this->error('平台类型参数错误');

        if($type=='user_miniapp'){
            $appid = config('site.user_miniapp_appid');
            $app_secret = config('site.user_miniapp_appsecret');

            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$app_secret&js_code=$code&grant_type=authorization_code";
            //$result = getCurl($url);
            $result = file_get_contents($url);
            $result = json_decode($result, true);

            if(isset($result['unionid'])){
                $this->success('成功',$result);
            }else{
                if(isset($result['errmsg']))
                    $this->error($result['errmsg']);
                $this->error('获取unionid出错');
            }
        }
        if($type=='driver_app'){
            $appid = config('site.driver_app_appid');
            $app_secret = config('site.driver_app_appsecret');

            $api="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$app_secret&code=$code&grant_type=authorization_code";

            $result=json_decode(file_get_contents($api),true);
            if(!isset($result['access_token'])){
                if(isset($result['errmsg']))
                    $this->error($result['errmsg']);
                $this->error('获取unionid出错');
            }

            $result_1=json_decode(file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token={$result['access_token']}&openid={$result['openid']}"),true);
            if(!isset($result_1['unionid'])){
                if(isset($result_1['errmsg']))
                    $this->error($result_1['errmsg']);
                $this->error('获取unionid出错');
            }

            $this->success('成功',$result_1);
        }

        $this->error('其他错误');
    }


    /**
     * 微信登录
     */
    public function wxLogin()
    {
        $open_id = $this->request->request('open_id');
        $union_id = $this->request->request('union_id');
        //$username = $this->request->request('nickname','');
        //$avatar = $this->request->request('avatar','');
        $username='';
        $avatar='';
        $mobile = $this->request->request('mobile','');

        $type=request()->param('type')?:'user_miniapp';

        if (!$union_id||$union_id=='undefined') {
            $this->error('缺少unionid，请在登陆时点击同意微信授权');
        }
        $user = UserModel::get(['wx_unionid'=>$union_id]);

        $check_mobile = $mobile?UserModel::getByMobile($mobile):[];

        if ($user) {
            if($user['status']=='writeOff'){
                $this->error('此账号已被注销');
            }
            if ($user->status != 'normal') {
                $this->error(__('账号异常!'));
            }
            if($type=='user_miniapp'){
                if (!$open_id||$open_id=='undefined') {
                    $this->error('缺少openid');
                }
                if(!$user['wx_miniapp_openid']){
                    $user['wx_miniapp_openid']=$open_id;
                    $user->save();
                }
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);

        } else {
            $avatar    = $avatar?:Config::get('site.default_avatar');
            $gender    = $this->request->request('gender',0);

            $extend      = [
                'username'      => $username?:'用户'.time().rand(1000,9999),
                'gender'        => $gender,
                'avatar'        => $avatar,
                'wx_unionid'      => $union_id
            ];
            if($type=='user_miniapp'){
                if (!$open_id) {
                    $this->error('缺少登陆信息');
                }
                $extend['wx_miniapp_openid']=$open_id;
            }

            $ret         = $this->auth->wxRegister($union_id,$extend);
        }
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $driver_info=DriverInfo::where(['user_id'=>$data['userinfo']['id']])
                ->field('name,status')
                ->find()?:null;
            $data['driverinfo']=$driver_info;
            $this->success(__('登陆成功!'),$data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 获取access_token
     */
    public function getAccessToken(){
        $appid = config('site.user_miniapp_appid');
        $app_secret = config('site.user_miniapp_appsecret');
        $api="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$app_secret";

        $result=json_decode(file_get_contents($api),true);

        if(!isset($result['access_token'])||!$result['access_token'])
            $this->error('获取AccessToken出错');

        return $result['access_token'];
    }

    /**
     * 获取微信个人资料
     */
    public function getWxPhone(){
        $code=request()->param('code');
        if(!$code)
            $this->error('code不能为空');

        $access_token=$this->getAccessToken();
        $api="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$access_token";

        $data=[
            'code'=>$code
        ];

        $result=Http::sendRequest($api,json_encode($data));

        if(!$result['ret'])
            $this->error($result['info']);

        $response=json_decode($result['msg'],true);

        if($response['errcode']!=0)
            $this->error($response['errmsg']);

        if(!$response['phone_info']['purePhoneNumber'])
            $this->error('获取手机号码为空');

        $this->success('成功',$response['phone_info']['purePhoneNumber']);
    }

    /**
     * 微信绑定手机号账号
     */
    public function wxBind()
    {
        $mobile   = $this->request->request('mobile');

        $mobile_user = UserModel::getByMobile($mobile);
        $user = $this->auth->getUser();
        if(!$user)
            $this->error('未找到账号信息，请重新注册');

        if($mobile_user){
            $mobile_user['wx_miniapp_openid']=$user['wx_miniapp_openid'];
            $mobile_user['wx_unionid']=$user['wx_unionid'];
            $mobile_user->save();

            if($user['id']!=$mobile_user['id'])
                $user->delete();

            $ret = $this->auth->direct($mobile_user['id']);
        }
        else{
            $user['mobile']=$mobile;
            $user['username']=$user['username']?:$mobile;
            $user->save();
            $this->auth->direct($user['id']);

            /*$password=Random::numeric(8);
            $this->auth->changepwd($password, '', true);
            \app\common\model\Sms::SendSms($password,$mobile,0,615750);*/
            $ret = $this->auth->direct($user['id']);
        }

        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('登陆成功!'),$data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 判断邀请码是否存在
     *
     * @param string $code
     *
     * @return bool
     */
    public static function is_exist($code)
    {
        $user = UserModel::where('invite_code',$code)->find();
        if ($user) {
            $code = Random::alnum();
            return self::is_exist($code);
        } else {
            return $code;
        }
    }

    /**
     * 修改实名信息.
     */
    public function realname()
    {
        $user = $this->auth->getUser();
        $realname = $this->request->request('realname','');
        $id_no = $this->request->request('id_no','');

        if($realname||$id_no){
            if(!$realname){
                $this->error('请输入真实姓名');
            }
            if(!$id_no){
                $this->error('请输入身份证号');
            }
            $user['realname'] = $realname;
            $user['id_no'] = $id_no;

            $user->save();
        }

        $this->success('成功',['realname'=>$user['realname'],'id_no'=>$user['id_no']]);
    }

    /**
     * 修改紧急联系人信息.
     */
    public function emergency()
    {
        $user = $this->auth->getUser();
        $emergency_contact_person = $this->request->request('emergency_contact_person','');
        $emergency_contact_phone = $this->request->request('emergency_contact_phone','');

        if($emergency_contact_person||$emergency_contact_phone){
            if(!$emergency_contact_person){
                $this->error('请输入紧急联系人姓名');
            }
            if(!$emergency_contact_phone){
                $this->error('请输入紧急联系人联系电话');
            }
            $user['emergency_contact_person'] = $emergency_contact_person;
            $user['emergency_contact_phone'] = $emergency_contact_phone;

            $user->save();
        }

        $this->success('成功',[
            'emergency_contact_person'=>$user['emergency_contact_person'],
            'emergency_contact_phone'=>$user['emergency_contact_phone']
        ]);
    }

    /**
     * 系统消息
     */
    public function notice(){
        $user = $this->auth->getUser();
        $type = request()->param('type')?:'user_miniapp';
        $page = request()->param('page')?:1;

        $where=[
            'user_id'=>$user['id']
        ];
        if($type=='user_miniapp'){
            $where['type']=0;
        }
        elseif($type=='worker_app'){
            $where['type']=1;
        }
        else{
            $this->error('平台类型参数错误');
        }

        $list=Notice::where($where)
            ->page($page,10)
            ->order('create_time desc')
            ->select()?:[];

        $this->success('成功',$list);
    }

    /**
     * 意见反馈
     */
    public function advice(){
        $user=$this->auth->getUser();

        $content=request()->param('content','');
        $img=request()->param('img','');
        $phone=request()->param('phone','');

        if(!$content){
            $this->error('请填写内容');
        }
        if(!$phone){
            $this->error('请填写联系电话');
        }

        $check_exist=Advice::where([
            ['user_id','=',$user['id']],
            ['create_time','>',time()-43200]
        ])
            ->find()?:[];
        if($check_exist)
            $this->error('12内提交过意见反馈，请过段时间再提交新的反馈');

        $result=Advice::insert([
            'user_id'=>$user['id'],
            'content'=>$content,
            'img'=>$img,
            'phone'=>$phone,
            'create_time'=>time()
        ]);

        if($result)
            $this->success('成功');
        else
            $this->error('添加意见反馈出错');
    }
}
